package com.rabbitmq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author lipengwei
 */
public class RabbitMqUtils {

    /**
     * rabbitmq 的连接工厂.
     */
    private static ConnectionFactory connectionFactory;

    static {
        // 类加载执行，只执行一次
        connectionFactory = new ConnectionFactory();
        // 设置连接rabbitmq主机
        connectionFactory.setHost("192.168.190.25");
        // 设置端口
        connectionFactory.setPort(5672);
        // 设置连接哪个虚拟主机
        connectionFactory.setVirtualHost("ems");
        // 设置访问虚拟主机的用户名密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("ems");
    }

    /**
     * 获取连接.
     * @return Connection
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }

    /**
     * 关闭通道和连接.
     * @param channel 通道
     * @param connection 连接
     */
    public static void closeChannelAndConnection(Channel channel, Connection connection) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
